package br.com.advance.automacao.web.administrativo;

import java.util.ArrayList;
import java.util.List;

import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import javax.faces.context.FacesContext;
import javax.faces.model.SelectItem;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;

import br.com.advance.automacao.model.CLP;
import br.com.advance.automacao.services.CLPService;
import br.com.advance.automacao.services.job.ColetorFimDeTurnoJob;
import br.com.advance.automacao.web.utils.BaseBean;

@ManagedBean
@ViewScoped
public class ColetarDadosCLPMBean extends BaseBean {

	private static final long serialVersionUID = 5299765946755355810L;

	private static final Logger logger = Logger.getLogger(ColetarDadosCLPMBean.class);

	@Autowired
	private ColetorFimDeTurnoJob coletorFimDeTurnoJob;

	@Autowired
	private CLPService clpService;

	private List<SelectItem> listCLPs = new ArrayList<SelectItem>();
	private Long idCLPSelecionado;

	public void initialize() {
		logger.info("initialize...");
		List<CLP> clps = clpService.buscarTodosAtivos();
		for(CLP clp : clps) {
			listCLPs.add(new SelectItem(clp.getId(), clp.getNome()));
		}
	}

	protected boolean verificaUsuarioLogado() {
		return true;
	}

	public void coletarDados() {
		if(idCLPSelecionado == null) {
			FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_WARN, "Nenhum Equipamento Selecionado.", null);
			FacesContext.getCurrentInstance().addMessage(null, message);
			return;
		}
		String retorno = coletorFimDeTurnoJob.coletarDadosFimTurno(idCLPSelecionado);
		if(retorno == null) {
			FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_INFO, "Operação realizada com sucesso", null);
			FacesContext.getCurrentInstance().addMessage(null, message);
		} else {
			FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_WARN, retorno, null);
			FacesContext.getCurrentInstance().addMessage(null, message);
		}
	}

	public List<SelectItem> getListCLPs() {
		return listCLPs;
	}

	public void setListCLPs(List<SelectItem> listCLPs) {
		this.listCLPs = listCLPs;
	}

	public Long getIdCLPSelecionado() {
		return idCLPSelecionado;
	}

	public void setIdCLPSelecionado(Long idCLPSelecionado) {
		this.idCLPSelecionado = idCLPSelecionado;
	}


}
